<?php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
class RaovatModelRaovats extends JModelLegacy{
	
	protected $_data = null;
	protected $_menu = null;
	
	protected $_total = null;
	protected $_pagination = null;
	public function __construct()
	{
		parent::__construct();
		$app    = JFactory::getApplication();
		$config = JFactory::getConfig();
		$this->setState('limit', $app->getUserStateFromRequest('com_search.limit', 'limit', $config->get('list_limit'), 'uint'));
		$this->setState('limitstart', $app->input->get('limitstart', 0, 'uint'));
		$this->setState('cat', $app->input->get('cat', 0, 'uint'));
	}
	
	public function getData()
	{
		if (empty($this->_data))
		{
			$db = JFactory::getDBO();
			$query = $db->getQuery(true);
			$query->select('*');
			$query->from('#__raovat');
			$query->where('published = 1');
			
			$cat = $this->getState('cat');
			if ($cat){
				$select = "select id from #__categories WHERE parent_id= '{$cat}'";
				
				$db->setQuery($select);
				$results = $db->loadObjectList();
				if ($results){
				 foreach ($results as $key=>$val){
				 	$temps[] = $val->id;
				 }
				 $temps = implode(',', $temps);
				 $query->where('category in ('.$temps.')');
				}else {
					$query->where('category = '.$cat);
				}
			}
			$query->order('id desc');
			
			$db->setQuery((string) $query,$this->getState('limitstart'),$this->getState('limit'));
			$this->_data = $db->loadObjectList();
		}
		return $this->_data;
	}
	
	public function getTotal()
	{
			$db = JFactory::getDBO();
			$query = $db->getQuery(true);
			$query->select('count(*)');
			$query->from('#__raovat');
			$query->where('published = 1');
			
			$cat = $this->getState('cat');
			if ($cat){
				$select = "select id from #__categories WHERE parent_id= '{$cat}'";
				
				$db->setQuery($select);
				$results = $db->loadObjectList();
				if ($results){
				 foreach ($results as $key=>$val){
				 	$temps[] = $val->id;
				 }
				 $temps = implode(',', $temps);
				 $query->where('category in ('.$temps.')');
				}else {
					$query->where('category = '.$cat);
				}
			}
			
			
			$db->setQuery((string) $query);
			$this->_total = $db->loadResult();
		return $this->_total;
	}

	public function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_pagination;
	}
	
}
